<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2019/1/15
 * Time: 23:05
 */
namespace app\api\logic;


use app\common\model\User;
use app\common\model\zbtask\Rate;
use app\common\utils\Utils;
use think\Db;
use think\exception\ValidateException;
use think\Model;

class RateLogic
{

    private static $new;
    private $rate;
    private $user_id;
    private $where = [];
    private function __construct() {
        $this->rate = new Rate();
    }


    public static function instance () { //声明一个静态公共方法，供外部获取唯一实例
        if (!(self::$new instanceof self)) {
            self::$new = new self;
        }
        return self::$new;
    }

    /**
     * 设置查询用户
     * @param $user_id
     * @return  object
     */
    public function setUserId($user_id) {
        $this->user_id = $user_id;
        return $this;
    }

    /**
     * 设置查询用户
     * @param $where
     * @return  object $this
     */
    public function where($where = []) {
        //设置where条件
        $this->where = array_merge($this->where, $where);
        return $this;
    }

    public function getMoneyList($type = 1, $where = []) {
        $this->where = array_merge($this->where, $where);
        if ($this->user_id) {
            $this->where['user_id'] = $this->user_id;
        }
        $list = $this->rate
            ->where($this->where)
            ->order('createtime desc')
            ->paginate()->each(function ($item, $key) {
                $item->create_time_text = Utils::time_format($item->createtime, 'Y-m-d');
            });

        return $list;
    }


    /**
     * 统计
     * @param array $where
     * @return double
     */
    public function moneySum($where=[]) {
        if ($this->user_id) {
            $this->where['user_id'] = $this->user_id;
        }
        $this->where = array_merge($this->where, $where);
        $sum = $this->rate->where($this->where)->sum('money') ?? 0.00;

        return $sum;
    }


    private function __clone() {} //声明私有的克隆方法，防止对象被克隆

    public function __sleep() { //重写__sleep方法，将返回置空，防止序列化反序列化获得新的对象
        return [];
    }

}